package com.simtop.hj.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.simtop.hj.common.ServerResponse;
import com.simtop.hj.pojo.ExcelPriceData;
import com.simtop.hj.pojo.QuestionGrade;
import com.simtop.hj.pojo.User;
import com.simtop.hj.service.QuestionService;
import com.simtop.hj.utils.ExcelUtils;
import com.simtop.hj.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@CrossOrigin
@RestController
@RequestMapping(value = "/question")
public class QuestionController {


    @Autowired
    public QuestionService questionService;


    private Logger logger=LoggerFactory.getLogger(QuestionController.class);

    /**
     * 根据编号获取到调查问卷信息
     * @param request
     * @param data
     * @return
     */
    @RequestMapping(value = "/getQuestion")
    public ServerResponse getQuestion(HttpServletRequest request, @RequestBody String data){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        JSONObject jsonObject= JSON.parseObject(data);
        String[] questions=jsonObject.getString("questionId").split(",");
        Integer pageNum=jsonObject.getInteger("pageNum");
        Integer pageSize=jsonObject.getInteger("pageSize");
        int[] questionIds=new int[questions.length];
        for (int i = 0; i <questions.length ; i++) {
            questionIds[i]=Integer.parseInt(questions[i]);
        }
        return questionService.getQuestion(questionIds,pageNum,pageSize);
    }


    /**
     * 根据回答数据省份统计
     * @param request
     * @return
     */
    @RequestMapping(value = "/provinceStatistics")
    public ServerResponse getProvinceStatistics(HttpServletRequest request){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        return questionService.provinceStatistics();
    }


    /**
     * 根据问题编号来作图
     * @param request
     * @param data
     * @return
     */
    @PostMapping(value = "/doPicture")
    public ServerResponse doPicture(HttpServletRequest request,@RequestBody String data){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        JSONObject jsonObject= JSON.parseObject(data);
        Integer questionId=jsonObject.getInteger("questionId");
        Integer category=jsonObject.getInteger("category");
        return questionService.doPicture(questionId,category);
    }

    /**
     * 提交成绩
     * @param request
     * @param data(grade 是成绩分数)
     * @return
     */
    @PostMapping(value = "/commitPartOneGrade")
    public ServerResponse commitPartOneGrade(HttpServletRequest request,@RequestBody String data){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject=JSON.parseObject(data);
        Double grade=jsonObject.getDouble("grade");
        return questionService.commitPartOneGrade(grade,u.getId());
    }


    /**
     *
     * @param request
     * @param data(grade 是成绩分数,gradeCategory是成绩模块：2是模块二、3是模块三、4是模块四)
     * @return
     */
    @PostMapping(value = "/commitPartGrade")
    public ServerResponse commitPartGrade(HttpServletRequest request,@RequestBody String data){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        JSONObject jsonObject=JSON.parseObject(data);
        Double grade=jsonObject.getDouble("grade");
        Integer gradeCategory=jsonObject.getInteger("gradeCategory");
        Integer questionGradeId=jsonObject.getInteger("questionGradeId");
        return questionService.commitPartGrade(grade,gradeCategory,questionGradeId);
    }

    /**
     * 用户获取到模块成绩(管理员能够查看到所有用户的成绩；学生和评审专家只能看到自己的模块成绩)
     * @param request
     * @return
     */
    @PostMapping(value = "/getModuleGrade")
    public ServerResponse getModuleGrade(HttpServletRequest request,@RequestBody String data){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject=JSON.parseObject(data);
        Integer pageNum=jsonObject.getInteger("pageNum");
        Integer pageSize=jsonObject.getInteger("pageSize");
        return questionService.getModuleGrade(u,pageNum,pageSize);
    }

    /**
     * 第二模块开始
     */


    /**
     * 获取红酒品牌
     * @return
     */
    @PostMapping(value = "/getWineBrand")
    public ServerResponse getWineBrand(@RequestBody String data){
        JSONObject jsonObject=JSON.parseObject(data);
        //红酒品牌等级（0为低级、1为中级、2为高级）
        int choose=jsonObject.getInteger("choose");
        return questionService.getWineBrand(choose);
    }


    /**
     * 获取到同档竞品次红酒价格趋势(折线图)
     * @param data
     * @return
     */
    @PostMapping(value = "getTendency")
    public ServerResponse getTendency(@RequestBody String data,HttpServletRequest request){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        JSONObject jsonObject=JSON.parseObject(data);
        String brandName=jsonObject.getString("brandName");
        String[] brandNameArray=brandName.split(",");
        return questionService.getTendency(brandNameArray);
    }


    /**
     * 三个模块的因素
     * @param data
     * @param request
     * @return
     */
    @PostMapping(value = "/getWineElement")
    public ServerResponse getWineElement(@RequestBody String data,HttpServletRequest request){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }

        JSONObject jsonObject=JSON.parseObject(data);
        String brandName=jsonObject.getString("brandName");
        String[] brandNameArray=brandName.split(",");
        return questionService.getWineElement(brandNameArray);
    }

    /**
     * 根据红酒品牌和红酒档次来获取各个价格的平均价
     * @param data
     * @param request
     * @return
     */
    @PostMapping(value = "/getWineAvg")
    public ServerResponse getWineAvg(@RequestBody String data,HttpServletRequest request){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt,User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        JSONObject jsonObject=JSON.parseObject(data);
        String brandName=jsonObject.getString("brandName");
        String productCategory=jsonObject.getString("productCategory");
        String[] brandNameArray=brandName.split(",");
        return questionService.getWineAvg(brandNameArray,productCategory);
    }

    /**
     * 计算方差和标准差
     * @param data
     * @return
     */
    @RequestMapping(value = "/calculatePrice",method = RequestMethod.POST)
    public ServerResponse calculatePrice(@RequestBody String data){
        JSONObject jsonObject=JSON.parseObject(data);
        String brandName=jsonObject.getString("brandName");
//        String productCategory=jsonObject.getString("productCategory");
        String month=jsonObject.getString("month");
        String[] monthArray=month.split(",");
        int[] months=new int[2];
        for (int i = 0; i < monthArray.length; i++) {
            months[i]=Integer.parseInt(monthArray[i]);
        }
        return questionService.calculatePrice(brandName,months);
    }




    /**
     * 下载竞品定价数据模板
     * @param response
     */
    @RequestMapping(value = "/uploadWineTemplate",method = RequestMethod.GET)
    public void uploadSongLyrics(HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "竞品定价数据模板";
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            ExcelUtils.writeExcel(out, ExcelPriceData.class,null);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
